package com.its.controller;


import com.its.domain.BaseResult;
import com.its.domain.CodeEnum;
import com.its.goods.pojo.Goods;
import com.its.goods.service.GoodsService;
import com.its.pojo.Cart;
import com.its.pojo.GoodsOrder;
import com.its.service.CartService;
import com.its.service.GoodsOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/goodsOrder")
public class GoodsOrderController {
    //注入业务层属性
    @Autowired
    private GoodsOrderService goodsOrderService;
    @Autowired
    private CartService cartService;
    @Autowired
    private GoodsService goodsService;


    /*@PostMapping("/creat")
    public BaseResult creatGoodsOrder(@RequestBody List<Cart> selectedItems, HttpServletRequest request) {
        String memberAccount = (String) request.getAttribute("memberAccount");
        if (memberAccount == null) {
            return BaseResult.error(CodeEnum.NOT_LOGIN_ERROR);
        }

        if (selectedItems == null || selectedItems.isEmpty()) {
            return BaseResult.error(CodeEnum.CART_EMPTY);
        }

        BigDecimal totalAmount = BigDecimal.ZERO;
        int totalQuantity = 0;
        StringBuilder goodsNames = new StringBuilder();

        GoodsOrder goodsOrder = new GoodsOrder();

        for (Cart cart : selectedItems) {
            Goods goods = goodsService.selectGoodsByIdService(cart.getGid());
            if (goods == null) {
                return BaseResult.error(CodeEnum.GOODS_NOT_FOUND);
            }

            // 计算总金额与商品数量
            goodsNames.append(cart.getGoodsName()).append(", ");
            totalQuantity += cart.getMount();

            goodsOrder.setPrice(goods.getGoodsPrice());

            // 检查库存
            if (goods.getGoodsInventory() < cart.getMount()) {
                return BaseResult.error(CodeEnum.INSUFFICIENT_STOCK);
            }

            totalAmount = totalAmount.add(goods.getGoodsPrice().multiply(BigDecimal.valueOf(cart.getMount())));
        }

        if (goodsNames.length() > 2) {
            goodsNames.setLength(goodsNames.length() - 2); // 去掉最后的 ", "
        }

        // 设置订单信息
        goodsOrder.setOrderId(generateGoodsOrderId());
        goodsOrder.setMemberAccount(memberAccount);
        goodsOrder.setGoodsName(goodsNames.toString());
        goodsOrder.setQuantity(totalQuantity);
        goodsOrder.setSubtotal(totalAmount);
        goodsOrder.setStatus("未处理");
        goodsOrder.setOrderTime(new Date());

        // 创建订单
        int i = goodsOrderService.creatGoodsOrder(goodsOrder);
        if (i != 1) {
            return BaseResult.error(CodeEnum.ORDER_CREATION_FAILED);
        }

        System.out.println("订单已经存入到数据库中");

        // 更新库存
        for (Cart cart : selectedItems) {
            Goods goods = goodsService.selectGoodsByIdService(cart.getGid());
            goods.setGoodsInventory(goods.getGoodsInventory() - cart.getMount());
            goodsService.updateGoods(goods);
        }

        System.out.println("进入到清除购物车环节");
        // 清空购物车
        for (Cart cart : selectedItems) {
            cartService.deleteToCart(cart.getId(), memberAccount);
        }
        System.out.println("将已经结算的物品清除出购物车");

        return BaseResult.ok(goodsOrder);
    }*/

    @PostMapping("/creat")
    public BaseResult creatGoodsOrder(@RequestBody List<Cart> selectedItems, HttpServletRequest request) {
        String memberAccount = (String) request.getAttribute("memberAccount");
        if (memberAccount == null) {
            return BaseResult.error(CodeEnum.NOT_LOGIN_ERROR);
        }

        if (selectedItems == null || selectedItems.isEmpty()) {
            return BaseResult.error(CodeEnum.CART_EMPTY);
        }

        BigDecimal totalAmount = BigDecimal.ZERO;
        int totalQuantity = 0;
        StringBuilder goodsNames = new StringBuilder();

        GoodsOrder goodsOrder = new GoodsOrder();

        for (Cart cart : selectedItems) {
            Goods goods = goodsService.selectGoodsByIdService(cart.getGid());
            if (goods == null) {
                return BaseResult.error(CodeEnum.GOODS_NOT_FOUND);
            }

            // 计算总金额与商品数量
            goodsNames.append(cart.getGoodsName()).append(", ");
            totalQuantity += cart.getMount();

            goodsOrder.setPrice(goods.getGoodsPrice());

            // 检查库存
            if (goods.getGoodsInventory() < cart.getMount()) {
                return BaseResult.error(CodeEnum.INSUFFICIENT_STOCK);
            }

            totalAmount = totalAmount.add(goods.getGoodsPrice().multiply(BigDecimal.valueOf(cart.getMount())));
        }

        if (goodsNames.length() > 2) {
            goodsNames.setLength(goodsNames.length() - 2); // 去掉最后的 ", "
        }

        // 设置订单信息
        goodsOrder.setOrderId(generateGoodsOrderId());
        goodsOrder.setMemberAccount(memberAccount);
        goodsOrder.setGoodsName(goodsNames.toString());
        goodsOrder.setQuantity(totalQuantity);
        goodsOrder.setSubtotal(totalAmount);
        goodsOrder.setStatus("未处理");
        goodsOrder.setOrderTime(new Date());

        // 创建订单
        int i = goodsOrderService.creatGoodsOrder(goodsOrder);
        if (i != 1) {
            return BaseResult.error(CodeEnum.ORDER_CREATION_FAILED);
        }

        System.out.println("订单已经存入到数据库中");

        // 更新库存
        for (Cart cart : selectedItems) {
            Goods goods = goodsService.selectGoodsByIdService(cart.getGid());
            goods.setGoodsInventory(goods.getGoodsInventory() - cart.getMount());
            goodsService.updateGoods(goods);
        }

        // 清空购物车中的商品
        for (Cart cart : selectedItems) {
            String Id = String.valueOf(cart.getId());
            System.out.println("购物车ID："+Id);
            cartService.deleteToCart(cart.getId(), memberAccount);  // 删除购物车中的商品
        }
        System.out.println("将已经结算的物品清除出购物车");

        return BaseResult.ok(goodsOrder);
    }




    private String generateGoodsOrderId(){
        //生成订单编号
        return "ORD" + System.currentTimeMillis();
    }


    //声明单元方法：根据用户名查询订单
    @GetMapping("/findByMemberAccount")
    public BaseResult findGoodsOrderByMemberAccount(HttpServletRequest request){
        String memberAccount = (String) request.getAttribute("memberAccount");
        return BaseResult.ok(goodsOrderService.selectGoodsOrderByMemberAccount(Integer.valueOf(memberAccount)));
    }


    //声明单元方法：查询所有订单
    @GetMapping("/search")
    public BaseResult search(Integer page,Integer size){
        return BaseResult.ok(goodsOrderService.selectAllGoodsOrder(page, size));
    }

    //声明单元方法：修改订单状态（管理员使用）
    /*@PutMapping("/update")
    public BaseResult updateGoodsOrderStatus(String orderId,String status){

    }*/
}
